package com.cicadasmall.initializer.quartz;

import com.cicadasmall.common.func.Fn;
import com.cicadasmall.data.domain.QuartzJobDO;
import com.cicadasmall.system.service.IQuartzJobService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * Quartz 初始化
 *
 * @author Jin
 */
@Slf4j
@Component
@Configuration
public class QuartzSchedulerJobInitializer implements CommandLineRunner {

    @Autowired
    private IQuartzJobService quartzJobService;

    @Override
    public void run(String... args) {
        log.info("========[ 开始初始化调度任务 ]========");
        List<QuartzJobDO> quartzJobList = quartzJobService.list();
        if (Fn.isEmpty(quartzJobList)) {
            log.info("没有可启动的任务");
        } else {
            quartzJobList.stream().parallel().forEach(this::accept);
        }
        log.info("========[ 调度任务初始化完成 ]========\n");
    }

    private void accept(QuartzJobDO quartzJobDO) {
        try {
            log.info("加载任务 - {}", quartzJobDO.getJobName());
            quartzJobService.schedulerJob(quartzJobDO);
        } catch (Exception e) {
            log.info("加载任务出错 - {}", e.getMessage());
            e.printStackTrace();
        }
    }
}
